import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Row,
  Select,
  Modal,
  Tooltip,
  Badge,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;

const { pathname } = window.location;

interface TableProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  loading: boolean;
  INITINFO: any;
  screen: string;
  hasPath: boolean;
}

interface TableState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  delVisbile: boolean;
  boxId: number;
  rowId:number;
}

@connect(
  ({
    cloudBoxList: { dataInfo },
    common: { INITINFO },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    INITINFO,
    screen,
    hasPath,
    loading: loading.effects['cloudBoxList/fetch'],
  }),
)
class CloudBoxElem extends React.Component<TableProps, TableState> {
  columns = [
    {
      title: '物流中心',
      dataIndex: 'logisName',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '云盒编码',
      dataIndex: 'boxCode',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      width: 160,
    },
    {
      title: '添加人',
      dataIndex: 'createUserName',
      width: 80,
    },
    {
      title: '授权主体',
      dataIndex: 'partnerId',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: 'token',
      dataIndex: 'partnerKey',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '自动打印订单',
      dataIndex: 'autoPrint',
      render: (val: number) => (val ? (
        <Badge status="success" text="已启动" style={{ color: '#87d068' }} />
      ) : (
        <Badge status="default" text="已关闭" style={{ color: '#999999' }} />
      )),
      width: 110,
    },
    {
      title: '操作',
      dataIndex: 'boxId',
      width: 60,
      render: (val: number) => (
        <span className="operLink" onClick={() => this.handleChangeDelModal(true, val)}>
          删除
        </span>
      ),
    },
  ];

  state: TableState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    delVisbile: false,
    boxId: 0,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchLogisList();

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'cloudBoxList/fetch',
      payload: this.getQueryParams(),
    });
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchLogisList' });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        pageIndex: 1,
        pageSize: 20,
        ...values,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '云盒管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '云盒管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '云盒管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  handleAddCloudBox = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '添加云盒',
      url: '/basic/cloudBoxManagement/list/add',
    });
  };

  /**
   * 点击删除云盒
   */
  handleChangeDelModal = (delVisbile: boolean, boxId: number = 0) => {
    this.setState({ delVisbile, boxId });
  };

  /**
   * 确定删除云盒
   */
  handleConfirmDelete = () => {
    const { boxId } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'cloudBoxList/delete',
      payload: {
        boxId,
        search: this.getQueryParams(),
      },
    });
    this.handleChangeDelModal(false);
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const { pageIndex, pageSize, delVisbile } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo = {},
      loading,
      INITINFO: { logisList },
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12} justify="space-between">
              <Col md={8} sm={24}>
                <Form.Item label="物流中心">
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card className="tableList" bordered={false}>
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddCloudBox}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="boxId"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          visible={delVisbile}
          title="确认操作"
          onOk={this.handleConfirmDelete}
          onCancel={() => this.handleChangeDelModal(false)}
        >
          <p>是否确认删除当前云盒？</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<TableProps>()(CloudBoxElem);
